#!/usr/bin/perl
use utf8;
binmode(STDIN, ':encoding(utf8)');
binmode(STDOUT, ':encoding(utf8)');
binmode(STDERR, ':encoding(utf8)');
use LWP::Simple qw(get);
use JSON        ;
use File::Slurp;
use Try::Tiny;
while(1) {

	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	$dayStamp=sprintf("%d%02d%02x", $year+1900, $mon+1,$mday);
	print "### LOOPING $dayStamp ###\n";
	

	my $scene= decode_json(read_file("db_scene.json"));
	foreach $key (keys $scene) {
		$lat = $scene->{$key}->{'lat'};
		$lon = $scene->{$key}->{'lon'};
		$try = 0;

		
		 $url     = "http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon";
again:
		try {
			$weather= from_json(get($url));
		} catch {
			print "get weather failed. do again after 5s";
			sleep(5);
			$try++;
			if($try < 5)  {
				goto again;
			}
		};
		$weatherTemp = $weather->{'main'}{'temp'} - 273;
		$weatherDesc = $weather->{'weather'}[0]->{'main'};

		$json_file="data/".$key.".txt.data".$dayStamp;
		system("touch $json_file");
		#print $json_file."\n";
		try {
			$tmp = read_file($json_file);
			 $decoded = decode_json($tmp);
		} catch {
			undef %decoded;
			print "$json_file may be a empty json file\n";
		};
		$decoded->{"$hour"."_temp"} =  $weatherTemp;
		$decoded->{"$hour"."_weather"} =  $weatherDesc;
		write_file($json_file, encode_json($decoded));
		$tmp = $key.".txt";
		system("chmod 777 data/*");
		system("wget 'http://162.243.140.106/visitors/count_top.php?place=$tmp' -O tmp");

		#printf("%s 溫度: %s 天氣: %s\n", $scene->{$key}->{'cname'},  $weatherTemp,  $weatherDesc);

		
	}
	print "ROUND END ################\n";
	sleep(3600);
}
